
/*
 * MIT License
 *
 * Copyright (c) 2020 wen.gu <454727014@qq.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

/***************************************************************************
 * Name: service_provider.h
 *
 * Purpose: service provider base class define
 *
 * Developer:
 *   wen.gu , 2021-05-28
 *
 * TODO:
 *
 ***************************************************************************/

/******************************************************************************
 **    INCLUDES
 ******************************************************************************/
#ifndef __SERVICE_PROVIDER_H__
#define __SERVICE_PROVIDER_H__

#include <tuple>
#include <memory>
#include <functional>

#include "deserializer.h"
#include "serializer.h"
#include "internal_impl.h"
#include "message.h"

/******************************************************************************
 **    MACROS
 ******************************************************************************/

/******************************************************************************
 **    TYPE DEFINITIONS
 ******************************************************************************/

/******************************************************************************
 **    CLASSES/FUNCTIONS DEFINITIONS
 ******************************************************************************/
class ServiceProvider
{
public:
    /** */
    using MethodHandler = std::function<void (MessagePtr)>;
    using Method_Id = uint32_t;
    using ServiceProviderPtr = std::shared_ptr<ServiceProvider>;
public:
    ServiceProvider(const std::string& service_name);
    virtual ~ServiceProvider();
public:
    static ServiceProviderPtr CreateService(ComProtocolType type, const std::string& service_name);
public:
    virtual bool OfferService() = 0;
    virtual bool StopService() = 0;
public:
    virtual bool RegisterReceiveHandler(MessageType type,  MessageId msg_id, MethodHandler handler) = 0;
    virtual DeserializerPtr GetDeserializer(Message::PayloadPtr payload) = 0;
    virtual SerializerPtr GetSerializer() = 0;
    virtual bool Send(MessagePtr msg) = 0;
    virtual MessagePtr MakeMessage(MessageType type) = 0;
public:
    template<class Provider, typename R, typename... Args>
    void HandleMethod(MethodId method_id, Provider* pr, R(Provider::* method)(Args...))
    {
        RegisterReceiveHandler(MessageType::kRequest, method_id, [this, pr](MessagePtr msg)
        {
            std::tuple<Args...> params;
            DeserializerPtr desp = GetDeserializer(msg->payload());
            if (desp)
            {
                bool parse_ret = true;
                for (size_t i = 0; i < sizeof ...(Args); i++)
                {
                    if (!desp->Deserialize(std::get<i>(params)))
                    {
                        parse_ret = false;
                        break;
                    }
                }

                if (parse_ret)
                {
                    /** todo, add this to std::async */
                    R ret = Apply(pr, method, params);
                    SerializerPtr serializer = GetSerializer();
                    serializer->Serialize(ret);
                    msg->set_payload(serializer->GetPayload());
                    msg->set_type(MessageType::kResponse);
                    return Send(msg);
                }
            }           
        });
    }
public:
    const std::string& service_name() const { return service_name_;}
protected:
    std::string service_name_;
}; 

#endif /** !__SERVICE_PROVIDER_H__ */